package com_fit.springboot_fit.controller;


import com_fit.springboot_fit.entity.AdminMenu;
import com_fit.springboot_fit.entity.AdminUser;
import com_fit.springboot_fit.service.AdminMenuService;
import com_fit.springboot_fit.service.AdminUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/menu")
public class MenuController {

    @Autowired
    private AdminMenuService menuService;

    @Autowired
    private AdminUserService userService;

    /**
     * 获取当前用户的菜单列表
     */
    @GetMapping("/currentUserMenus")
    public Map<String, Object> getCurrentUserMenus() {
        Map<String, Object> result = new HashMap<>();

        try {
            String loginName = SecurityContextHolder.getContext().getAuthentication().getName();
            AdminUser user = userService.findByLoginName(loginName)
                    .orElseThrow(() -> new RuntimeException("用户不存在"));

            List<AdminMenu> menus = menuService.getMenusByUserId(user.getId());

            result.put("code", 200);
            result.put("data", menus);

        } catch (Exception e) {
            result.put("code", 500);
            result.put("message", e.getMessage());
        }

        return result;
    }

    /**
     * 检查权限
     */
    @GetMapping("/checkPermission")
    public Map<String, Object> checkPermission(
            @RequestParam String m,
            @RequestParam String c,
            @RequestParam String a) {

        Map<String, Object> result = new HashMap<>();

        try {
            String loginName = SecurityContextHolder.getContext().getAuthentication().getName();
            AdminUser user = userService.findByLoginName(loginName)
                    .orElseThrow(() -> new RuntimeException("用户不存在"));

            boolean hasPermission = menuService.checkMenuPermission(user.getId(), m, c, a);

            result.put("code", 200);
            result.put("data", hasPermission);

        } catch (Exception e) {
            result.put("code", 500);
            result.put("message", e.getMessage());
        }

        return result;
    }
}
